<?php
// +----------------------------------------------------------------------
// | CRMEB [ CRMEB赋能开发者，助力企业发展 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2016~2023 https://www.crmeb.com All rights reserved.
// +----------------------------------------------------------------------
// | Licensed CRMEB并不是自由软件，未经许可不能去掉CRMEB相关版权
// +----------------------------------------------------------------------
// | Author: CRMEB Team <admin@crmeb.com>
// +----------------------------------------------------------------------

namespace app\services\pay;


use app\services\BaseServices;
use app\services\order\StoreOrderDeliveryServices;
use app\services\order\StoreOrderInvoiceServices;
use app\services\order\StoreOrderServices;
use app\services\order\StoreOrderStatusServices;
use app\jobs\ProductLogJob;
use app\services\user\UserServices;
use app\services\statistic\CapitalFlowServices;
use crmeb\exceptions\ApiException;
use stdClass;
use think\facade\Cache;
use think\facade\Db;
use app\api\controller\v2\LogController;
class SmfpayServices extends BaseServices
{
    protected $key = NULL;
    protected $message_key = NULL;
    protected $services = NULL;
    protected $mercCode = NULL;
    protected $agentCode = NULL;
    protected $subProCode = NULL;

    public function __construct()
    {
        $this->key = "lbWecTu0Zjvi4b18WkBndO3bzkdp7GTKNYau2jG4csEw8HHoyuDt8aJKCOv8QCvb"; // 签名密钥
        $this->message_key = "J1BbO69F"; // 报文密钥
        $this->mercCode = 'MER0000000003942';//商户号
        $this->agentCode = 'AGT0000000000582';//代理商号
        $this->subProCode='1782601908356255';//子产品编号
        $this->url='https://smf.jingweitech.cn:8443';//正式环境


//        $this->key = "P6JafGO9QU2fTyASvyyD0KXHsnsokw3sh7Vx1obA6ygAiAoLsjwxThjfLCyXvatI"; // 签名密钥
//        $this->message_key = "KRH9keYRyuVuRVm0LNMQoEX7qSDISv5VMgYHe3gL87wkmUQIY2F1NsCnAWX7oYvQ"; // 报文密钥
//        $this->mercCode = 'MER0000000003942';//商户号
//        $this->agentCode = 'AGT0000000000171';//代理商号
////      $this->subProCode='1740291488769773';//子产品编号分账
//        $this->subProCode='1781218678063370';//子产品编号不分账
//        $this->url='http://test.app.jingweitech.cn:8280';//测试环境

    }

    //#扫码付
    public function smfpay($data){
        //区别哪套小程序
        $app_config = Db::name('wechat_pay_config')->where('id',$data['appid'])->find();
//        p($app_config);exit;
        if(!$app_config)exception('App theme error!');
        $app =  Db::name('smf_applyment')->where('id',$data['vendorid'])->find();
        if(!$app)exception('APP NULL');
        $config1['outTradeNo'] = $data['orderon'];
        $config1['mercCode'] = $app['mercCode'];//商户号
        $config1['orderAmount'] = $data['amount'];//金额
        $config1['clientType'] = 'MINI';
        $config1['appId'] = "wx0c7526a3baf45449";
        $config1['tradeDesc'] = $data['body'];
        $config1['timeExpire'] = 5;//订单过期时间1分钟
        $notify_url = $app_config['smf_notify_url']; // 接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
        $config1['notifyUrl'] = $notify_url;
        $config1['termIp'] = $this->get_client_ip();//IP
        $config1['frontNotifyUrl'] = 'https://pay.test.com/Order/order_list/';//前端支付成功后跳转路径
        $config1['productCapability'] = 'WECHAT_JS_PAY';
        $fz_amount = bcmul($data['amount'],0.1,2);
        if($fz_amount>0&&$app['id']!=2){//分账金额大于0才分账并且不等于约你游
            $saccPayeeList []= ['saccPayeeCode'=>'MER0000000003932','saccAmount'=>$fz_amount];//分账收款方列表
            $config1['saccInfo']=['saccWay'=>"SYNC",'saccValidDay'=>1,'saccNotifyUrl'=>'http://ttt.com','saccPayeeList'=>$saccPayeeList];;
        }
        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
        $headers = ['Content-Type: application/json; charset=utf-8'];
        $pay_res = http_post_json($this->url."/api/trade/cashierPreOrder.html", $config,$headers);//正式

        if ($pay_res['respMsg'] == "成功") {
            $respData = $this->decryptStr($pay_res['respData'],$this->message_key);
            $respData = json_decode($respData,true);
            return $respData;
        } else {
            if ($pay_res['respCode'] == "PAY0009") {
                $db = Db::name('yny_log')->where('yny_post_data', 'like', '%' . $data['orderon'] . '%')->find();
                $time = bcsub(time(), $db['addtime']);
                if ($time >= 300) exception("订单已过有效支付期，请重新下单！");
                $json_db = json_decode($db['wx_post_data'], true);
                return $json_db;
//            }
                exception($pay_res['respMsg']);
            }
        }
    }


    //#扫码付
    public function smfpay_back($data){
        //区别哪套小程序
        $app_config = Db::name('wechat_pay_config')->where('id',$data['appid'])->find();
        if(!$app_config)exception('App theme error!');
        $app =  Db::name('smf_applyment')->where('id',$data['vendorid'])->find();
        if(!$app)exception('APP NULL');
        $config1['outTradeNo'] = $data['orderon'];
        $config1['mercCode'] = $app['mercCode'];//商户号
        $config1['orderAmount'] = $data['amount'];//金额
        $config1['clientType'] = 'APP';
        $config1['tradeDesc'] = $data['body'];
        $config1['timeExpire'] = 5;//订单过期时间1分钟
        $notify_url = $app_config['smf_notify_url']; // 接收微信支付异步通知回调地址，通知url必须为直接可访问的url，不能携带参数。
        $config1['notifyUrl'] = $notify_url;
        $config1['termIp'] = $this->get_client_ip();//IP
        $config1['frontNotifyUrl'] = 'https://pay.test.com/Order/order_list/';//前端支付成功后跳转路径
        $fz_amount = bcmul($data['amount'],0.1,2);
        if($fz_amount>0&&$app['id']!=2){//分账金额大于0才分账并且不等于约你游
            $saccPayeeList []= ['saccPayeeCode'=>'MER0000000003932','saccAmount'=>$fz_amount];//分账收款方列表
            $config1['saccInfo']=['saccWay'=>"SYNC",'saccValidDay'=>1,'saccNotifyUrl'=>'http://ttt.com','saccPayeeList'=>$saccPayeeList];;
        }
        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
        $headers = ['Content-Type: application/json; charset=utf-8'];
        $pay_res = http_post_json($this->url."/api/trade/cashierPreOrder.html", $config,$headers);//正式
        if ($pay_res['respMsg'] == '成功') {
            $respData = $this->decryptStr($pay_res['respData'],$this->message_key);
            $respData = json_decode($respData,true);
            return $respData;
        } else {
            if($pay_res['respCode']=='PAY0009'){
                $db = Db::name('yny_log')->where('yny_post_data','like','%'.$data['orderon'].'%')->find();
                $time = bcsub(time(),$db['addtime']);
                if($time>=300)exception("订单已过有效支付期，请重新下单！");
                $json_db = json_decode($db['wx_post_data'],true);
                return $json_db;
            }
            exception($pay_res['respMsg']);
        }
    }

    /*
    * 扫码付退款
    * */
    public function smf_refund($data)
    {
        //区别哪套小程序
        $app_config = Db::name('wechat_pay_config')->where('id',$data['appid'])->find();
        if(!$app_config)exception('App theme error!');
        $config1['payOutTradeNo'] = $data['payOutTradeNo'];
        $config1['outTradeNo'] = $data['outTradeNo'];
        $config1['refundAmount'] = $data['refundAmount'];//金额
        $notify_url = $app_config['smf_notify_url']; // 后台回调地址
        $config1['notifyUrl'] = $notify_url;
        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
        $headers = ['Content-Type: application/json; charset=utf-8'];
        $pay_res = http_post_json($this->url."/api/trade/refund.html", $config,$headers);//正式
        if ($pay_res['respMsg'] == '成功') {
            $respData = $this->decryptStr($pay_res['respData'],$this->message_key);
            $respData = json_decode($respData,true);
            return $respData;
        } else {
            exception($pay_res['respMsg']);
        }
    }
    /*
     * 扫码富商户进件
     * */
    public function smf_subApplyment($data)
    {
        $arr = $data;
        $id = $data['id'];//约你游app传过来的会员id
        if($id==0)exception('会员id不能为0!');
        $check = Db::name('smf_applyment')->where('uid',$id)->where('applyment_state','<>',"已驳回")->find();
        if($check)exception('已提交资料申请，无需重复提交！');
        $contact_info = $data['contact_info'];//【基本信息】
        $z1 = json_encode($contact_info);
        $subject_info = $data['subject_info'];//【主体资料】
        $z2 = json_encode($subject_info);
        $business_info = $data['business_info'];//【经营资料】
        $z3 = json_encode($business_info);
        $bank_account_info = $data['bank_account_info'];//【结算银行账户】
        $z4 = json_encode($bank_account_info);

        //判断企业资料是否存在于库，同一企业不能多次提交
        $license_number = $subject_info['business_license_info']['license_number'];//公司代码
        $sh_name = $arr['shopName'];
        $as = Db::name('smf_applyment')->where(['license_number'=>$license_number,'name'=>$sh_name])->find();
        if($as)exception('该企业已提交资料申请！');

        $rateList []= ['rateType'=>'WECHAT','tradeRate'=>0.5];//费率类型列表
        $rateList []= ['rateType'=>'ALIPAY','tradeRate'=>0.5];//费率类型列表
        $rateList []= ['rateType'=>'YSF_CREDIT_SMALL','tradeRate'=>0.5];
        $rateList []= ['rateType'=>'YSF_CREDIT_BIG','tradeRate'=>0.65];
        $rateList []= ['rateType'=>'YSF_DEBIT_SMALL','tradeRate'=>0.5];
        $rateList []= ['rateType'=>'YSF_DEBIT_BIG','tradeRate'=>0.55,'cappedAmount'=>20];
        $data = [
            //子产品编号
            'subProCode'     =>  $this->subProCode,
            //基本信息
            'baseInfo'      =>[
                'mercType'=>$subject_info['subject_type'],//商户类型
                'mercName'=>$subject_info['business_license_info']['merchant_name'],//商户注册名称
                'mercShortName'=>$subject_info['business_license_info']['merchant_name'],//商户营业名称
                'industryType1'=>$business_info['industryType1'],//行业一类     NO
                'industryType2'=>$business_info['industryType2'],//行业二类     NO
                'industryType3'=>$business_info['industryType3'],//行业三类     NO
                'phone'=>$contact_info['mobile_phone'],//管理员手机号
                'principal'=>$contact_info['contact_name'],//负责人
                'principalPhone'=>$contact_info['mobile_phone'],//负责人手机号
                'upMercCode'=>'MER0000000003932'//上级商户
            ],
            //经营信息
            'businessInfo'      =>[
                'busLicImg'=>$subject_info['business_license_info']['license_copy'],//营业执照照片
                'busLicNo'=>$subject_info['business_license_info']['license_number'],//营业执照
                'registeredName'=>$subject_info['business_license_info']['merchant_name'],//营业执照名称

                'registeredCapital'=>$business_info['registeredCapital'],//注册资本 NO
                'busLicStartDate'=>$business_info['busLicStartDate'],//营业执照开始时间 NO
                'busLicEndDate'=>$business_info['busLicEndDate'],//营业执照结束时间 NO
                'registeredProvCode'=>$business_info['registeredProvCode'],//注册地址省编号 NO
                'registeredCityCode'=>$business_info['registeredCityCode'],//注册地址市编号 NO
                'registeredAreaCode'=>$business_info['registeredAreaCode'],//注册地址区编号 NO
                'registeredAddress'=>$business_info['registeredAddress'],//详细地址 NO
                'businessScope'=>$business_info['businessScope'],//经营范围 NO

                'legalCertType'=>$subject_info['identity_info']['id_doc_type'],//法人证件类型  YES
                'legalCertName'=>$subject_info['identity_info']['id_doc_info']['id_doc_name'],//法人证件姓名
                'legalCertNumber'=>$subject_info['identity_info']['id_doc_info']['id_doc_number'],//法人证件编号
                'legalCertFrontImg'=>$subject_info['identity_info']['id_doc_info']['id_doc_copy'],//法人证件正面照
                'legalCertReverseImg'=>$subject_info['identity_info']['id_doc_info']['id_doc_copy_back'],//法人证件反面照
                'legalCertStartDate'=>$subject_info['identity_info']['id_doc_info']['doc_period_begin'],//法人证件有效期开始日期
                'legalCertEndDate'=>$subject_info['identity_info']['id_doc_info']['doc_period_end'],//法人证件有效期截止日期
                'legalPhone'=>$contact_info['mobile_phone'],//法人手机号
                'contactCertType'=>$subject_info['identity_info']['id_doc_type'],//联系人证件类型  YES
                'contactCertName'=>$subject_info['identity_info']['id_doc_info']['id_doc_name'],//联系人证件姓名
                'contactCertNumber'=>$subject_info['identity_info']['id_doc_info']['id_doc_number'],//联系人证件编号
                'contactCertFrontImg'=>$contact_info['contact_id_doc_copy'],//联系人证件正面照822
                'contactCertReverseImg'=>$contact_info['contact_id_doc_copy_back'],//联系人证件反面照822
                'contactCertStartDate'=>$subject_info['identity_info']['id_doc_info']['doc_period_begin'],//联系人证件有效期开始日期
                'contactCertEndDate'=>$subject_info['identity_info']['id_doc_info']['doc_period_end'],//联系人证件有效期截止日期
                'contactEmail'=>$contact_info['contact_email'],//联系人邮箱
                'contactPhone'=>$contact_info['mobile_phone'],//联系人手机号
                'doorHeadImg'=>$business_info['doorHeadImg'],//门头照 NO
                'cashierDeskImg'=>$business_info['cashierDeskImg'],//收银台照 NO
                'indoorImg'=>$business_info['indoorImg'],//室内照 NO
            ],
            //费率信息(rateList)
            'rateList'  =>$rateList,

            //结算信息(settleInfo)
            'settleInfo'        =>[
                'settleAccountType'=>$bank_account_info['bank_account_type'],//结算账户类型
                'settleCycle'=>'T1',//结算周期T1、D1、D0
                'accountNo'=>$bank_account_info['account_number'],//账号
                'accountName'=>$bank_account_info['account_name'],//户名
                'accountImg'=>$bank_account_info['accountImg'],//银行账户照片    NO
                'bankCode'=>$bank_account_info['bankCode'],//行别    NO
                'subBranchNo'=>$bank_account_info['subBranchNo'],//支行号    NO
                'subBranchName'=>$bank_account_info['subBranchName'],//支行名称    NO
            ],
        ];

        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($data, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($data, JSON_UNESCAPED_UNICODE)), $this->message_key);
        $headers = ['Content-Type: application/json; charset=utf-8'];
        $url = $this->url."/api/merc/merc/addMerc.html";//测试
        $data2 = http_post_json($url, $config,$headers);
        if($data2['respMsg']=="系统繁忙，请稍后重试")exception("信息填写有误，请核对后再填写！");
        if($data2['respMsg']!="成功")exception($data2['respMsg']);
        //解密
        $res = $this->decryptStr($data2['respData'],$this->message_key);
        $res = json_decode($res,true);
        if (empty($applyment_id = $res['applyOrderNo'])) {
            exception('[applyOrderNo]返回错误！');
        }
        //插入自己数据库数据
        $list = [
            'contact_info'=>$z1,
            'subject_info'=>$z2,
            'business_info'=>$z3,
            'bank_account_info'=>$z4,
            'add_time'=>time(),
            'applyment_id'=>$applyment_id,
            'applyment_state'=>'已提交',
            'name'=>$arr['shopName'],
            'shopAddress'=>$arr['shopAddress'],
            'longitude'=>$arr['longitude'],
            'latitude'=>$arr['latitude'],
            'trade_stardate'=>$arr['trade_stardate'],
            'trade_enddate'=>$arr['trade_enddate'],
            'headImg'=>$arr['headlmg'],
            'license_number'=>$license_number
        ];
        if(isset($arr['sources']))$list['sources']=$arr['sources'];
        $check_applyment =  Db::name('smf_applyment')->where('uid',$id)->where('applyment_state',"已驳回")->find();//如果是已驳回的状态重新提交
        if($check_applyment){
            Db::name('smf_applyment')->where('uid',$id)->update($list);//驳回重新提交
        }else{
            $list['uid'] = $id;
            $ynydzId = Db::name('smf_applyment')->insertGetId($list);//第一次提交成功获取店铺id
            $shopName = $arr['shopName'];
            $shopAddress = $arr['shopAddress'];
            $headImg = "https://ynytest-1300951025.cos.ap-chengdu.myqcloud.com/ynymanage/20240510/78d35ddc1420d14afc1987f1654a0b0a762f.png";
            $longitude = $arr['longitude'];
            $latitude = $arr['latitude'];
            $trade_stardate = $arr['trade_stardate'];
            $trade_enddate = $arr['trade_enddate'];
            $MerchantMemberId = $id;//会员id

            if($arr['sources']=='user'){//推送用户端数据
                $yny_Data = [
                    'shopName'=>$shopName,//商户名称
                    'shopAddress'=>$shopAddress,//商户地址
                    'headImg'=>$headImg,//商户头部照片
                    'longitude'=>$longitude,//经度
                    'latitude'=>$latitude,//纬度
                    'smf_id'=>$ynydzId,//扫码富商户入驻ID
                    'ynydzId'=>0,//扫码富商户入驻ID
                    'trade_stardate'=>$trade_stardate,//营业开始时间
                    'trade_enddate'=>$trade_enddate,//营业结束时间
                    'MerchantMemberId'=>$MerchantMemberId,//约你游会员id
                    'busLicImg'=>''//营业执照
                ];
                $this->ApplyTourShop($yny_Data);
            }else{//推送导游端数据
                //获取下载地址
//                $img_code = $subject_info['business_license_info']['license_copy'];
//                $abc['imageCode'] = $img_code;
//                $this->getImageDownloadUrl($abc);
                $yny_Data2 = [
                    'company_type'=>0,//$subject_info['subject_type'],//主体类型
                    'company_code'=>$subject_info['business_license_info']['license_number'],//公司代码
                    'name'=>$arr['shopName'],//公司名称
                    'corporation'=>$subject_info['identity_info']['id_doc_info']['id_doc_name'],//法人名称
                    'corporation_idtype'=>0,//$subject_info['identity_info']['id_doc_type'],//法人证件类型
                    'corporation_name'=>$subject_info['business_license_info']['merchant_name'],//法人公司名称
                    'corporation_address'=>$business_info['registeredAddress'],//法人地址
                    'corporation_idcardno'=>$subject_info['identity_info']['id_doc_info']['id_doc_number'],//法人身份证号
                    'corporation_idcard_begin'=>$subject_info['identity_info']['id_doc_info']['doc_period_begin'],//法人身份证有效期开始
                    'corporation_idcard_end'=>$subject_info['identity_info']['id_doc_info']['doc_period_end'],//法人身份证有效期结束
                    'memberid'=>$MerchantMemberId,//用户id
                    'company_img'=>"",
                ];

                $this->add_merchants($yny_Data2);
            }
        }
        return 1;
    }

    //手动推送约你游商家数据1
    public function post_ynyvendor($data){
        $arr = Db::name('smf_applyment')->where('uid',$data['uid'])->find();//查询
        $shopName = $arr['name'];
        $shopAddress = $arr['shopAddress'];
        $headImg = "https://ynytest-1300951025.cos.ap-chengdu.myqcloud.com/ynymanage/20240510/78d35ddc1420d14afc1987f1654a0b0a762f.png";
        $longitude = $arr['longitude'];
        $latitude = $arr['latitude'];
        $trade_stardate = $arr['trade_stardate'];
        $trade_enddate = $arr['trade_enddate'];
        $MerchantMemberId = $data['uid'];//会员id
        $yny_Data = [
            'shopName'=>$shopName,
            'shopAddress'=>$shopAddress,
            'headImg'=>$headImg,
            'longitude'=>$longitude,
            'latitude'=>$latitude,
            'smf_id'=>$arr['id'],
            'ynydzId'=>$arr['id'],
            'trade_stardate'=>$trade_stardate,
            'trade_enddate'=>$trade_enddate,
            'MerchantMemberId'=>$MerchantMemberId,
            'busLicImg'=>''//营业执照
        ];
        $this->ApplyTourShop($yny_Data);
    }

    //手动推送约你游商家数据2 邱邱用2025年1月7日15:41:35
    public function post_ynyvendor2($data){
        $arr = Db::name('smf_applyment')->where('uid',$data['uid'])->find();//查询
        $subject_info = json_decode($arr['subject_info'],true);
        $business_info = json_decode($arr['business_info'],true);//【经营资料】
        $MerchantMemberId = $arr['uid'];//会员id
        $yny_Data = [
                'company_type'=>0,//$subject_info['subject_type'],//主体类型
                'company_code'=>$subject_info['business_license_info']['license_number'],//公司代码
                'name'=>$arr['name'],//公司名称
                'corporation'=>$subject_info['identity_info']['id_doc_info']['id_doc_name'],//法人名称
                'corporation_idtype'=>0,//$subject_info['identity_info']['id_doc_type'],//法人证件类型
                'corporation_name'=>$subject_info['business_license_info']['merchant_name'],//法人公司名称
                'corporation_address'=>$business_info['registeredAddress'],//法人地址
                'corporation_idcardno'=>$subject_info['identity_info']['id_doc_info']['id_doc_number'],//法人身份证号
                'corporation_idcard_begin'=>$subject_info['identity_info']['id_doc_info']['doc_period_begin'],//法人身份证有效期开始
                'corporation_idcard_end'=>$subject_info['identity_info']['id_doc_info']['doc_period_end'],//法人身份证有效期结束
                'memberid'=>$MerchantMemberId,//用户id
                'company_img'=>'https://yizuche-1300951025-1300951025.cos.ap-nanjing.myqcloud.com/car/416752025011510160292.jpg'
        ];
        $this->add_merchants($yny_Data);
    }

    /*
     * 调约你游接口申请店铺
     * */
    public function ApplyTourShop($yny_Data){
//        $yny_Data = [
//            'shopName'=>"强盛",
//            'shopAddress'=>"地址信息",
//            'headImg'=>"",
//            'longitude'=>'115.2',
//            'latitude'=>'95.3',
//            'ynydzId'=>2,
//            'trade_stardate'=>"08:00",
//            'trade_enddate'=>"22:00",
//            'MerchantMemberId'=>88929766,
//        ];
//        $url = "https://apiv2.ta.klch.cn//api/NewActivity/ApplyTourShop";//测试
        // 要同步的表名
//        $table2 = 'ux_smf_applyment';
//        // 获取正式库的数据
//        $dataFromDb1 =  Db::table('ux_smf_applyment')->select()->toArray();
//        // 清空测试库的数据
//        Db::connect('test')->table($table2)->where(1)->delete();
//        // 将正式库数据插入测试数据库
//        Db::connect('test')->table($table2)->insertAll($dataFromDb1);

        $url = "https://apiv2.ynyapp.com/api/NewActivity/ApplyTourShop";//正式
        $headers = [ 'Content-Type: application/json; charset=utf-8'];
        $arr = http_post_json($url,$yny_Data,$headers);
        if($arr['status']==1){
            return 1;
        }
        return true;
    }

    //导游端同步商家数据 2025年1月7日16:37:22
    public function add_merchants($yny_Data2){
        $url = "https://aitravel.ynyapp.com/api/tb_merchants/add_merchants";//正式
//        $url = "https://travelcs.ynyapp.com/api/tb_merchants/add_merchants";//测试
        $headers = [ 'Content-Type: application/json; charset=utf-8'];
        $arr = http_post_json($url,$yny_Data2,$headers);
        if($arr['status']==1){
            return 1;
        }
        return true;
    }

    /*
     * 扫码富获取行业编号
     * */
    public function get_smf_mcc(){
        $cache_smf_mcc = Cache::get('smf_mcc');
        if(!$cache_smf_mcc){
            $smf_mcc = Db::table('ux_smf_mcc')->field('id,name,topid,level')->where('level',1)->select()->toArray();
            foreach($smf_mcc as $k => $v){
                $smf_mcc[$k]['mcc'] = Db::name('smf_mcc')->field('id,name,level')->where('topid',$v['id'])->select()->toArray();
                foreach($smf_mcc[$k]['mcc'] as $kk=>$vv){
                    $smf_mcc[$k]['mcc'][$kk]['mcc2'] = Db::name('smf_mcc')->field('id,name,level,topid')->where('topid',$vv['id'])->select()->toArray();
                }
            }
            Cache::set('smf_mcc', $smf_mcc, 86400);
        }else{
            $smf_mcc = $cache_smf_mcc;
        }
        return $smf_mcc;
    }

    /*
     * 扫码富获取银行编号
     * */
    public function get_bank_code(){
        //【结算银行账户类型】
        $get_bank_account_type = [
            ['value'=>'PUBLIC','text'=>'对公'],
            ['value'=>'PRIVATE','text'=>'对私']
        ];
        //【开户银行】
        $get_bank = [
            ['value'=>'102','text'=>'中国工商银行'],
            ['value'=>'103','text'=>'中国农业银行'],
            ['value'=>'104','text'=>'中国银行'],
            ['value'=>'105','text'=>'中国建设银行'],
            ['value'=>'203','text'=>'中国农业发展银行'],
            ['value'=>'301','text'=>'交通银行'],
            ['value'=>'302','text'=>'中信银行'],
            ['value'=>'303','text'=>'中国光大银行'],
            ['value'=>'304','text'=>'华夏银行'],
            ['value'=>'305','text'=>'中国民生银行'],
            ['value'=>'306','text'=>'广发银行'],
            ['value'=>'307','text'=>'平安银行'],
            ['value'=>'308','text'=>'招商银行'],
            ['value'=>'309','text'=>'兴业银行'],
            ['value'=>'310','text'=>'上海浦东发展银行'],
            ['value'=>'313','text'=>'城市商业银行'],
            ['value'=>'314','text'=>'农村商业银行'],
            ['value'=>'316','text'=>'浙商银行'],
            ['value'=>'318','text'=>'渤海银行'],
            ['value'=>'320','text'=>'村镇银行'],
            ['value'=>'403','text'=>'中国邮政储蓄银行'],
            ['value'=>'999','text'=>'其他银行'],
        ];
        $data['get_bank_account_type'] = $get_bank_account_type;
        $data['get_account_bank'] = $get_bank;
        return $data;
    }

    /*
     * 根据银行编号查询该银行下面所有支行信息
     * */
    public function get_bank_branch($data){
        $size = 100;
        $where = [];
        if($data['sub_branch_no']){
            $where[] =['sub_branch_no','like','%'.$data['sub_branch_no'].'%'];
        }
        if($data['sub_branch_name']){
            $where[] = ['sub_branch_name','like','%'.$data['sub_branch_name'].'%'];
        }
        $get_bank_branch = Db::table('bank_branch')
            ->field('bank_code,sub_branch_no,sub_branch_name')
            ->where(['bank_code'=>$data['bank_id'],'prov_code'=>$data['prov_code']])
            ->where($where)
            ->limit((($data['page'] - 1) * $size),$size)
            ->select()
            ->toArray();
        $count = Db::table('bank_branch')
            ->field('bank_code,sub_branch_no,sub_branch_name')
            ->where(['bank_code'=>$data['bank_id'],'prov_code'=>$data['prov_code']])
            ->where($where)
            ->count();
        $res['list'] = $get_bank_branch;
        $res["page"]=$data['page'];
        $res["total"]=$count;
        $res["size"]=$size;
        return $res;
    }

    //省市区编码
    public function get_smf_city_code(){
        $cache_city = Cache::get('smf_city');
        if(!$cache_city){
            $city = Db::table('ux_smf_city')->field('name,area_code as sheng_code,topid')->where('area_type','省')->select()->toArray();
            foreach($city as $k => $v){
                $city[$k]['place'] = Db::name('smf_city')->field('name,area_code as shi_code,topid')->where('topid',$v['sheng_code'])->select()->toArray();
                foreach($city[$k]['place'] as $kk=>$vv){
                    $city[$k]['place'][$kk]['qu'] = Db::name('smf_city')->field('name,area_code as qu_code')->where('topid',$vv['shi_code'])->select()->toArray();
                }
            }
            Cache::set('smf_city', $city, 86400);
        }else{
            $city = $cache_city;
        }
        return $city;
    }

    /*
     * 扫码富获取图片下载地址
     * */
    public function getImageDownloadUrl($data){
        $config1['imageCode'] = $data['imageCode'];
        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
        //https://smf.jingweitech.cn:8443/api/other/getImageDownloadUrl.html
        $res = http_post_json($this->url."/api/other/getImageDownloadUrl.html", $config,['Content-Type: application/json; charset=utf-8']);//正式
        if($res['respMsg']!="成功")exception($res['respMsg']);
        //解密
        $res = $this->decryptStr($res['respData'],$this->message_key);
        $res = json_decode($res,true);
        return $res;
    }

    /*
    * 查询商户审核结果
    * */
    public function queryCheckResult($data){
        if(!$data['uid'])throw new \Exception("未能处理正确请求");
        $smf_applyment = 0;//0未提交1已提交（审核中）2已驳回 3待签约 4已完成
        $smf_applyment_list = Db::name('smf_applyment')->where(['uid'=>$data['uid']])->find();
        if($smf_applyment_list){
            $data['applyOrderNo'] = $smf_applyment_list['applyment_id'];
        }
        if(!$smf_applyment_list)return ["checkType"=>'',"status"=>'',"signMethod"=>'','operate'=>'no'];
        if($smf_applyment_list){// 查询商户审核结果
            $config1['applyOrderNo'] = $smf_applyment_list['applyment_id'];
            $config['nonce'] = time();
            $config['agentCode'] = $this->agentCode; //代理商号
            $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
            $sing = $this->ASCIISHA256($config, $this->key);
            $config['sign'] = $sing;
            $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
            $res = http_post_json($this->url."/api/merc/merc/queryCheckResult.html", $config,['Content-Type: application/json; charset=utf-8']);//正式
            if($res['respMsg']!="成功")exception($res['respMsg']);
            //解密
            $res = $this->decryptStr($res['respData'],$this->message_key);
            $res = json_decode($res,true);
            if($res['status']) {
                switch ($res['status']) {
                    case "SUCCESS":
                        $smf_applyment = "成功";
                        break;
                    case "PROCESSING":
                        $smf_applyment = "处理中";
                        break;
                    case "FAIL":
                        $smf_applyment = "失败";
                        break;
                    default:
                }
            }
            if(!isset($res['signMethod'])){
                $res['signMethod'] = '';
            }
            //后门
            if($data['uid']==77268){
                $smf_applyment = "成功";
            }
            //后门
            $res['status'] = $smf_applyment;
            if(isset($res['mercCode'])){
                Db::name('smf_applyment')->where('id',$smf_applyment_list['id'])->update(['mercCode'=>$res['mercCode']]);
            }
        }
        $operate = 'ing';
        if(isset($res['signStatus'])){
            switch ($res['signStatus']) {
                case "NOT_NEED":
                    $operate = "rz";
                    break;
                case "NEED":
                    $operate = "qy";
                    $res['status']=$res['status']."<待签约>";
                    break;
                case "WAITING":
                    $operate = "qy";
                    $res['status']=$res['status']."<待签约>";
                    break;
                case "SUCCESS":
                    $operate = "rz";
                    break;
                default:
            }
        }
        //后门
        if($data['uid']==77268){
            $operate = "rz";
        }
        //后门
        if($smf_applyment=='失败')$operate = 'update';
        $res['operate'] = $operate;
        if($operate=='qy'){
            $rz =  $this->smf_Sign($data);
            $res['signMethod'] = $rz['econtractUrl'];
        }
        if($operate=='rz'&&$smf_applyment_list['mercCode']){
           $rz =  $this->getRealNameAuthInfo($smf_applyment_list);
            $field = 'authStatus';
            $valueToFind  = 'SUCCESS';
            $result = array_filter($rz, function ($item) use ($field,$valueToFind) {
                return isset($item[$field]) && $item[$field] === $valueToFind;
            });
            $count = count($result);
           if($count==2){
               $res['operate'] = "ok";
               $smf_applyment = "成功入驻";
           }
            $res['signMethod'] = $rz;
        }
        $update = Db::name('smf_applyment')->where('id',$smf_applyment_list['id'])->update(['applyment_state'=>$smf_applyment]);
        return $res;
    }
    /*
     * 发起签约
     * 商户进件且通道需要签约，通过此接口发起签约。签约状态为待签约，才能发起签约。
     * */
    public function smf_Sign($data){
        $config1['applyOrderNo'] = $data['applyOrderNo'];
        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
        $res = http_post_json($this->url."/api/merc/merc/sign.html", $config,['Content-Type: application/json; charset=utf-8']);//正式
        if(!$res)exception("数据异常");
        if($res['respMsg']!="成功")exception($res['respMsg']);
        //解密
        $res = $this->decryptStr($res['respData'],$this->message_key);
        $res = json_decode($res,true);
        return $res;
    }

    /*
     *  校验签约短信
    * */
    public function verifySignedSms($data){
        $config1['applyOrderNo'] = $data['applyOrderNo'];
        $config1['smsCode'] = $data['smsCode'];
        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
        $res = http_post_json($this->url."/api/merc/merc/verifySignedSms.html", $config,['Content-Type: application/json; charset=utf-8']);//正式
        if(!$res)exception("数据异常");
        if($res['respMsg']!="成功")exception($res['respMsg']);
        //解密
        $res = $this->decryptStr($res['respData'],$this->message_key);
        $res = json_decode($res,true);
        return $res;
    }

    /*
    *  获取实名认证信息
    * */
    public function getRealNameAuthInfo($data){
        $config1['mercCode'] = $data['mercCode'];
//        $config1['processId'] = $data['processId'];
        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
        $res = http_post_json($this->url."/api/merc/merc/getRealNameAuthInfo.html", $config,['Content-Type: application/json; charset=utf-8']);//正式
        if(!$res)exception("数据异常");
        if($res['respMsg']!="成功")exception($res['respMsg']);
        //解密
        $res = $this->decryptStr($res['respData'],$this->message_key);
        $res = json_decode($res,true);
        return $res;
    }

    /*
     * 查询余额
     * */
    public function queryBalance($data){
        $config1['mercCode'] = $data['mercCode'];
        $config['nonce'] = time();
        $config['agentCode'] = $this->agentCode; //代理商号
        $config['reqData'] = stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE));
        $sing = $this->ASCIISHA256($config, $this->key);
        $config['sign'] = $sing;
        $config['reqData'] = $this->encryptStr(stripslashes(json_encode($config1, JSON_UNESCAPED_UNICODE)), $this->message_key);
        //https://smf.jingweitech.cn:8443/api/other/getImageDownloadUrl.html
        $res = http_post_json($this->url."/api/sacc/queryBalance.html", $config,['Content-Type: application/json; charset=utf-8']);//正式
        if($res['respMsg']!="成功")exception($res['respMsg']);
        //解密
        $res = $this->decryptStr($res['respData'],$this->message_key);
        $res = json_decode($res,true);
        return $res;
    }
    /**
     * ASCII排序
     * @param array $params
     * @param $key
     * @return bool|string
     */
    public function ASCIISHA256($params = array(), $key)
    {
        if (!empty($params)) {
            $params = array_filter($params);
            $p = ksort($params);
            if ($p) {
                $str = '';
                foreach ($params as $k => $val) {
                    $val = trim($val);
                    if ($val === '' || $val === null) {
                        continue;
                    }
                    $str .= $k . '=' . $val . '&';
                }
                $strs = rtrim($str, '&');
                $stringSignTemp = $strs . '&key=' . $key;
                $re = hash('sha256', $stringSignTemp, true);
                return strtoupper(bin2hex($re));
            }
        }
        return false;
    }


    /**
     * des 加密
     * str 需要加密的账号
     * key 加密秘钥
     */
    public function encryptStr($str, $key)
    {
        $data = mb_convert_encoding($str, 'UTF-8');
        $encry = openssl_encrypt($data, 'DES-ECB', $key, OPENSSL_RAW_DATA);
        return base64_encode($encry);
    }

    /**
     * 解密
     */
    public function decryptStr($data, $key)
    {
        $decry = openssl_decrypt(base64_decode($data), 'DES-ECB', $key, OPENSSL_RAW_DATA);
        return $decry;
    }
    /**
     * 业务编号
     * @return string
     */
    private function getBusinessCode()
    {
        return date('Ymd') . substr(time(), -2) . substr(microtime(), 3, 4) . sprintf('%02d', rand(0, 99));
    }
    //获取ip
    function get_client_ip(){
        if (getenv("HTTP_CLIENT_IP") && strcasecmp(getenv("HTTP_CLIENT_IP"), "unknown")){
            $ip = getenv("HTTP_CLIENT_IP");
        }else if (getenv("HTTP_X_FORWARDED_FOR") && strcasecmp(getenv("HTTP_X_FORWARDED_FOR"), "unknown")){
            $ip = getenv("HTTP_X_FORWARDED_FOR");
        }else if (getenv("REMOTE_ADDR") && strcasecmp(getenv("REMOTE_ADDR"), "unknown")){
            $ip = getenv("REMOTE_ADDR");
        }else if (isset($_SERVER['REMOTE_ADDR']) && $_SERVER['REMOTE_ADDR'] && strcasecmp($_SERVER['REMOTE_ADDR'], "unknown")){
            $ip = $_SERVER['REMOTE_ADDR'];
        }else{
            $ip = "unknown";

        }
        return($ip);
    }
}